package o2o.web.actions.sys;

import com.jinyou.utils.common.AjaxResult;
import com.jinyou.utils.common.DateUtils;
import com.jinyou.utils.common.ObjectUtils;
import com.jinyou.utils.common.ValidateUtil;
import o2o.cache.sys.SysVariablePaotuiMemory;
import o2o.cache.user.UserInfoMemory;
import o2o.cache.user.UserOnlineImpl;
import o2o.config.dao.UserDaoSql;
import o2o.dao.PO.PojoTables;
import o2o.dao.PO.sys.SYS_VARIABLE_PAOTUI;
import o2o.dao.PO.sys.SysVariablePaotui;
import o2o.dao.PO.user.UserInfo;
import o2o.dao.VO.agent.CityAgentVO;
import o2o.dao.VO.sys.SysVariablePaotuiVO;
import o2o.web.actions.agent.CityAgentMan;
import o2o.web.actions.user.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//跑腿系统变量

@Controller
public class SysVariablePaotuiAction {

    //------------------------新版
    //获取配送费计算方式(根据所选位置的信息及类型code，获取对应的公式)
    @RequestMapping(method = RequestMethod.POST, value = "/sys/variable/paotui/info")
    @ResponseBody
    public String sys_variable_info(String token, String city, Double lat, Double lng, Integer code) {
        if (ValidateUtil.isNotAbsInteger(code)) {
            return AjaxResult.errorResult("请选择类型");
        }

        if (ValidateUtil.isNotNull(city)) {
            if (ValidateUtil.isNotLatLng(lat, lng)) {
                return AjaxResult.errorResult("经纬度不能为空");
            }
            //根据所在城市及经纬度获取最新的商圈
            CityAgentVO cityAgent = CityAgentMan.getCityAgent(city, lat, lng);
            if (null == cityAgent) {
                return AjaxResult.errorResult("您所在的位置尚未开通，请重新选择");
            }
            SysVariablePaotuiVO vo = infoOfAgentAndCode(cityAgent.getId(), code);
            return AjaxResult.successResult(vo);
        } else {
            SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(code);
            return AjaxResult.successResult(sysVariablePaotui);
        }
    }


    //根据商圈id获取
    @RequestMapping(method = RequestMethod.POST, value = "/agent/sys/variable/paotui/list")
    @ResponseBody
    public String agent_sys_variable_list(String token, Long agentId) {
        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("商圈不能为空");
        }

        List<SysVariablePaotuiVO> voList = listOfAgentId(agentId);
        if (!ValidateUtil.isAbsList(voList)) {
            return AjaxResult.successResult(0, null);
        }
        return AjaxResult.successResult(voList.size(), voList);
    }

    //获取商圈下某一种类信息里的
    @RequestMapping(method = RequestMethod.POST, value = "/agent/sys/variable/paotui/info")
    @ResponseBody
    public String agent_sys_variable_info(String token, Long agentId, Integer code) {
        if (ValidateUtil.isNotID(agentId)) {
            return AjaxResult.errorResult("商圈不能为空");
        }
        if (ValidateUtil.isNotAbsInteger(code)) {
            return AjaxResult.errorResult("请选择类型");
        }

        SysVariablePaotuiVO vo = infoOfAgentAndCode(agentId, code);
        return AjaxResult.successResult(vo);
    }

    //-----------------------平台
    // 货运信息获取信息等
    @RequestMapping(method = RequestMethod.POST, value = "/agent/sys/variable/paotui/tipPaotuiId/info")
    @ResponseBody
    public String agent_sys_variable_info(Long agentId, Integer code, Long tipPaotuiId) {
        if (ValidateUtil.isNotAbsInteger(code)) {
            return AjaxResult.errorResult("类型不能为空");
        }
        if (ValidateUtil.isNotID(tipPaotuiId)) {
            return AjaxResult.errorResult("车辆id不能为空");
        }

        SysVariablePaotuiVO vo = infoOfAgentAndCodeAndTipPaotuiId(agentId, code, tipPaotuiId);
        if (vo != null) {
            return AjaxResult.successResult(vo);
        }
        return AjaxResult.successResult();
    }

    //获取跑腿代购变量
    @RequestMapping(method = RequestMethod.POST, value = "/sys/variable/paotui/list")
    @ResponseBody
    public String sys_variable_list(String token, Long agentId, Integer code) {
        //验证用户有效性
//        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
//        if (user == null) {
//            return AjaxResult.errorLogoutResult();
//        }

        if (ValidateUtil.isID(agentId)) {
            List<SysVariablePaotuiVO> voList = listOfAgentId(agentId);
            if (ValidateUtil.isAbsList(voList)) {
                return AjaxResult.successResult(voList.size(), voList);
            }
        } else {
            if (ValidateUtil.isNotAbsInteger(code)) {
                List<SysVariablePaotui> list = SysVariablePaotuiMemory.getInstance().list();
                if (ValidateUtil.isAbsList(list)) {
                    List<SysVariablePaotuiVO> voList = new ArrayList<SysVariablePaotuiVO>();
                    for (int i = 0; i < list.size(); i++) {
                        if (null == list.get(i)) {
                            continue;
                        }
                        if (0 != 1 - list.get(i).getIsShow()) {
                            continue;
                        }
                        SysVariablePaotuiVO variablePaotuiVO = new SysVariablePaotuiVO();
                        try {
                            ObjectUtils.copyPropertiesExclude(list.get(i), variablePaotuiVO, null);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        }
                        voList.add(variablePaotuiVO);
                    }
                    return AjaxResult.successResult(voList.size(), voList);
                }
            } else {
                //获取某一类型的
                SysVariablePaotui info = SysVariablePaotuiMemory.getInstance().getByCode(code);
                if (null != info) {
                    SysVariablePaotuiVO vo = new SysVariablePaotuiVO();
                    try {
                        ObjectUtils.copyPropertiesExclude(info, vo);
                    } catch (Exception e) {
                        e.printStackTrace();
                        return AjaxResult.successResult(0, null);
                    }
                    List<SysVariablePaotuiVO> voList = new ArrayList<>();
                    voList.add(vo);
                    return AjaxResult.successResult(voList.size(), voList);
                }
            }

        }


        return AjaxResult.successResult(0, null);
    }

    //修改跑腿变量
    @RequestMapping(method = RequestMethod.POST, value = "/sys/variable/paotui/modify")
    @ResponseBody
    public String sys_variable_modify(String token, SysVariablePaotuiVO info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        if (ValidateUtil.isNotID(info.getAgentId())) {
            //验证是否有登录权限
            if (!User.getInstance().hasSuperAdminAuth(user.getUserType())) {
                return AjaxResult.errorResult("您没有访问权限");
            }
        } else {
            //验证是否有登录权限
            if (!User.getInstance().hasAdminAuth(user.getUserType())) {
                return AjaxResult.errorResult("您没有访问权限");
            }
        }


        if (null == info) {
            return AjaxResult.errorResult("请选择您要修改的数据");
        }
        if (ValidateUtil.isNotAbsInteger(info.getCode())) {
            return AjaxResult.errorResult("请选择您要修改的数据");
        }
        SysVariablePaotui sysVariablePaotui = null;
        if (ValidateUtil.isNotID(info.getId())) {
            sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByCode(info.getCode());
        } else {
            sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getById(info.getId());
        }

        if (null == sysVariablePaotui) {
            return AjaxResult.errorResult("未找到该条数据，请查证");
        }
        String extraStr = "";
        if (info.getCode() - SYS_VARIABLE_PAOTUI.BAO_XIAN == 0) {
            if (ValidateUtil.isNull(info.getName())) {
                return AjaxResult.errorResult("保险名称不能为空");
            }
            if (ValidateUtil.isNull(info.getRang())) {
                return AjaxResult.errorResult("保险代码不能为空");
            }
            if (ValidateUtil.isNull(info.getVal())) {
                return AjaxResult.errorResult("单价不能为空");
            }
            if (ValidateUtil.isNull(info.getPre())) {
                return AjaxResult.errorResult("是否必须购买不能为空");
            }
            extraStr += " ,extra1= '" + (ValidateUtil.isNull(info.getExtra1()) ? "" : info.getExtra1()) + "' ";
            if (ValidateUtil.isNull(info.getExtra1())) {
                return AjaxResult.errorResult("保险电话不能为空");
            }
            try {
                Double.parseDouble(info.getVal());
            } catch (Exception ex) {
                return AjaxResult.errorResult("请输入有效的数值");
            }
        } else {
            if (ValidateUtil.isNull(info.getName())) {
                return AjaxResult.errorResult("名称不能为空");
            }
            if (ValidateUtil.isNull(info.getRang())) {
                return AjaxResult.errorResult("范围不能为空");
            }
            if (ValidateUtil.isNull(info.getVal())) {
                return AjaxResult.errorResult("起步价不能为空");
            }
            if (ValidateUtil.isNull(info.getPre())) {
                return AjaxResult.errorResult("超出后每公里价格不能为空");
            }
            try {
                Double.parseDouble(info.getRang());
                Double.parseDouble(info.getVal());
                Double.parseDouble(info.getPre());
            } catch (Exception ex) {
                return AjaxResult.errorResult("请输入有效的数值");
            }
        }

        StringBuffer sb = new StringBuffer();
        sb.append("update ").append(PojoTables.SYS_VARIABLE_PAOTUI).append(" set name = '").append(info.getName())
                .append("',rang = '").append(info.getRang()).append("',val = '").append(info.getVal())
                .append("',pre = '").append(info.getPre()).append("',note = '").append(info.getNote()).append("',descs = '").append(info.getDescs())
                .append("',updateUser = '").append(user.getUsername()).append("' ").append(extraStr).append(" where delFlag = 0 and id = ").append(sysVariablePaotui.getId());
        System.out.println("修改跑腿配置:" + sb.toString());
        try {
            UserDaoSql.getInstance().executeBySql(sb.toString());
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("修改失败，请稍后再试");
        }

        //修改缓存
        SysVariablePaotuiMemory.getInstance().modify(sysVariablePaotui.getId());

        return AjaxResult.successResult();
    }

    //新增跑腿变量
    @RequestMapping(method = RequestMethod.POST, value = "/sys/variable/paotui/add")
    @ResponseBody
    public String sys_variable_add(String token, SysVariablePaotui info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("输入信息不能为空");
        }
        if (ValidateUtil.isNotAbsInteger(info.getCode())) {
            return AjaxResult.errorResult("类型不能为空");
        }


        SysVariablePaotui sysVariablePaotui = SysVariablePaotuiMemory.getInstance().getByAgentAndCode(info.getAgentId(), info.getCode());
        if (null != sysVariablePaotui) {
            return AjaxResult.errorResult("已有该类型的设置，请直接修改");
        }
        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("名称不能为空");
        }
        if (ValidateUtil.isNull(info.getRang())) {
            return AjaxResult.errorResult("范围不能为空");
        }
        if (ValidateUtil.isNull(info.getVal())) {
            return AjaxResult.errorResult("起步价不能为空");
        }
        if (ValidateUtil.isNull(info.getPre())) {
            return AjaxResult.errorResult("超出后每公里价格不能为空");
        }

        try {
            Double.parseDouble(info.getRang());
            Double.parseDouble(info.getVal());
            Double.parseDouble(info.getPre());
        } catch (Exception ex) {
            return AjaxResult.errorResult("请输入有效的数值");
        }

        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setCreateUser(user.getUsername());
        info.setIsShow(1);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_VARIABLE_PAOTUI, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }

        //修改缓存
        SysVariablePaotuiMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }

    //新增跑腿变量(主要是跑腿提示id在次数添加)
    @RequestMapping(method = RequestMethod.POST, value = "/sys/variable/paotui/add/v2")
    @ResponseBody
    public String sys_variable_add_v2(String token, SysVariablePaotui info) {
        //验证用户有效性
        UserInfo user = UserInfoMemory.getInstance().getUserInfo(UserOnlineImpl.getInstance().get(token));
        if (user == null) {
            return AjaxResult.errorLogoutResult();
        }

        //验证是否有登录权限
        if (!User.hasAdminAuth(user.getUserType())) {
            return AjaxResult.errorResult("您没有访问权限");
        }

        if (null == info) {
            return AjaxResult.errorResult("输入信息不能为空");
        }
        if (ValidateUtil.isNotAbsInteger(info.getCode())) {
            return AjaxResult.errorResult("类型不能为空");
        }

        if (ValidateUtil.isNull(info.getName())) {
            return AjaxResult.errorResult("名称不能为空");
        }
        if (ValidateUtil.isNull(info.getRang())) {
            return AjaxResult.errorResult("范围不能为空");
        }
        if (ValidateUtil.isNull(info.getVal())) {
            return AjaxResult.errorResult("起步价不能为空");
        }
        if (ValidateUtil.isNull(info.getPre())) {
            return AjaxResult.errorResult("超出后每公里价格不能为空");
        }
        if (ValidateUtil.isNotID(info.getTipPaotuiId())) {
            return AjaxResult.errorResult("跑腿提示id不能为空");
        }

        try {
            Double.parseDouble(info.getRang());
            Double.parseDouble(info.getVal());
            Double.parseDouble(info.getPre());
        } catch (Exception ex) {
            return AjaxResult.errorResult("请输入有效的数值");
        }

        Long time = DateUtils.getCurrTime();
        info.setCreateTime(time);
        info.setCreateUser(user.getUsername());
        info.setIsShow(1);

        try {
            UserDaoSql.getInstance().insertObj(PojoTables.SYS_VARIABLE_PAOTUI, info);
        } catch (SQLException e) {
            e.printStackTrace();
            return AjaxResult.errorResult("新增失败，请稍后再试");
        }

        //修改缓存
        SysVariablePaotuiMemory.getInstance().add(time);

        return AjaxResult.successResult();
    }


    //---------------------------------------------------------
    //商圈下的所有
    private List<SysVariablePaotuiVO> listOfAgentId(Long agentId) {
        if (ValidateUtil.isNotID(agentId)) {
            return null;
        }
        List<SysVariablePaotui> list = SysVariablePaotuiMemory.getInstance().listOfAgent(agentId);
        if (!ValidateUtil.isAbsList(list)) {
            return null;
        }
        List<SysVariablePaotuiVO> voList = new ArrayList<SysVariablePaotuiVO>();
        for (int i = 0; i < list.size(); i++) {
            SysVariablePaotui info = list.get(i);
            if (null == info) {
                continue;
            }
            if (0 != 1 - info.getIsShow()) {
                continue;
            }
            SysVariablePaotuiVO variablePaotuiVO = new SysVariablePaotuiVO();
            try {
                ObjectUtils.copyPropertiesExclude(info, variablePaotuiVO);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }
            voList.add(variablePaotuiVO);
        }
        return voList;
    }

//    //商圈下获取只给你的
//    public static SysVariablePaotuiVO infoOfAgentAndCodeAndTipPaotuiId(Long agentId, Integer code, Long tipPaotuiId) {
//        if (ValidateUtil.isNotAbsInteger(code) || ValidateUtil.isNotID(tipPaotuiId)) {
//            return null;
//        }
//        List<SysVariablePaotui> list = SysVariablePaotuiMemory.getInstance().listOfByAgentIdAndCode(agentId, code);
//
//        if (!ValidateUtil.isAbsList(list)) {
//            return null;
//        }
//        SysVariablePaotui sys = null;
//        for (SysVariablePaotui sysVariablePaotui : list) {
//            if (sysVariablePaotui == null) {
//                continue;
//            }
//            if (ValidateUtil.isNotID(sysVariablePaotui.getTipPaotuiId())) {
//                continue;
//            }
//            if (sysVariablePaotui.getTipPaotuiId().longValue() - tipPaotuiId == 0) {
//                sys = sysVariablePaotui;
//                break;
//            }
//        }
//
//        if (null == sys) {
//            return null;
//        }
//        SysVariablePaotuiVO vo = new SysVariablePaotuiVO();
//        try {
//            ObjectUtils.copyPropertiesExclude(sys, vo);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        return vo;
//    }

    //商圈下的某一个
    public static SysVariablePaotuiVO infoOfAgentAndCode(Long agentId, Integer code) {
        if (ValidateUtil.isNotID(agentId) || ValidateUtil.isNotAbsInteger(code)) {
            return null;
        }
        SysVariablePaotui info = SysVariablePaotuiMemory.getInstance().getByAgentAndCode(agentId, code);
        if (null == info) {
            //商圈没有  获取平台的
            info = SysVariablePaotuiMemory.getInstance().getByCode(code);
        }

        if (null == info) {
            return null;
        }
        SysVariablePaotuiVO vo = new SysVariablePaotuiVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, vo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }

    //货运活去商圈配置信息
    public static SysVariablePaotuiVO infoOfAgentAndCodeAndTipPaotuiId(Long agentId, Integer code, Long tipPaotuiId) {
        if (ValidateUtil.isNotAbsInteger(code) || ValidateUtil.isNotAbsLong(tipPaotuiId)) {
            return null;
        }
        SysVariablePaotui info = SysVariablePaotuiMemory.getInstance().getByAgentIdAndCodeAndTipPaotuiId(agentId, code, tipPaotuiId);
        if (null == info) {
            //商圈没有  获取平台的
            info = SysVariablePaotuiMemory.getInstance().getDeFalutByCodeAndTipPaotuiId(code, tipPaotuiId);
        }
        if (null == info) {
            return null;
        }
        SysVariablePaotuiVO vo = new SysVariablePaotuiVO();
        try {
            ObjectUtils.copyPropertiesExclude(info, vo);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return vo;
    }


}
